<?php

class events
{
	var $mess;
	var $tracks = Array();
	var $champid;
	var $dates = Array();
	var $capacity = Array();
	var $password = Array();
	var $toRender = Array();

	function events($champid)
	{
		$mess = '';
		$this->champid = $champid;
		if(isset($_POST['removeRecord']) && isset($_POST['id']))
		{
			$this->doDelete();
		}
		else if(isset($_POST['addRecord']) && isset($_POST['id']))
		{
			$this->doAdd();
		}
		else if(isset($_POST['editRecord']) && isset($_POST['id']))
		{
			$this->doEdit();
		}
		
		global $db;
		//tracks
		$q = 'SELECT t_id, t_fullTitle FROM ' . TRACKS_TABLE . ', ' . CHAMPIONSHIPS_TABLE .
                    ' WHERE t_game = c_game and c_id = ' . $this->champid  . ' ORDER BY t_fullTitle';
		$result = $db->sql_query($q);
		while($row = $db->sql_fetchrow($result)) 
		{
			$this->tracks[] = $row;
		}
		
		$this->setupEdit();
		$this->setupAdd();
	}

	function render()
	{		
		include_once('includes/addMessage.php');
		
		if($this->mess != '')
		{
			$this->mess->render();
		}
		
		foreach( $this->toRender as $key => $value){
			$value->render();
		}
		
	}
	
	function doDelete()
	{
		global $skin_dir, $db, $lang;
		
		//get the record
		$qSel = "select e_title, e_championship from ". EVENTS_TABLE . " Where e_id = " . $_POST['id'];
		$result = $db->sql_query($qSel);
		if($row = $db->sql_fetchrow($result)) 
		{
			$qDel = "delete from ". EVENTS_TABLE . " Where e_id = " . $_POST['id'];
			$db->sql_query($qDel);
			$qDel = "delete from ". EVENTDATES_TABLE . " Where ed_event = " . $_POST['id'];
			$db->sql_query($qDel);
			$qUpdateChamps = 'UPDATE ' . CHAMPIONSHIPS_TABLE . ' SET ' . 
					'c_firstRace=(SELECT ed_date FROM ' . EVENTDATES_TABLE . ' , ' . 
					DIVISIONS_TABLE . ' where ed_division = d_id  AND d_champid = ' .  
					$this->champid  . ' ORDER BY ed_date ASC LIMIT 0, 1),' . 
					'c_lastRace=(SELECT ed_date FROM ' . EVENTDATES_TABLE . ' , ' . 
					DIVISIONS_TABLE . ' where ed_division = d_id  AND d_champid = ' .  
					$this->champid  . ' ORDER BY ed_date DESC LIMIT 0, 1)' . 
					' WHERE c_id = ' . $this->champid;
			$db->sql_query($qUpdateChamps);
			$this->mess = new addMessage(str_replace('{entry}', $row['e_title'], $lang['AdminRemoved']), $lang['AdminRemovedTitle']);
			
		}
		else
		{
			$this->mess = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
			
		}
	}
	
	function doAdd()
	{
		global $db, $lang;
		
		if($this->validateFields(false)) 
		{
			$qUpd = "insert into  ". EVENTS_TABLE . " (e_title, e_championship, e_track, e_opensignups, e_description, " 
							. "e_preevent, e_postevent) values('" .
								 $_POST['title'] . "', " . 
								 $this->champid . ", " . 
								 $_POST['track'] . ", " . 
								 $_POST['active']  . ', "' . 
								 $_POST['description'] . '", "' . 
								 $_POST['preevent'] . '", "' . 
								 $_POST['postevent'] . '")';
			$db->sql_query("LOCK TABLES ". EVENTS_TABLE . "  WRITE");
			$db->sql_query("SET AUTOCOMMIT = 0");
			$db->sql_query($qUpd);
			$insertID = $db->sql_nextid();
			$db->sql_query("COMMIT");
			$db->sql_query("SET AUTOCOMMIT = 1");
			$db->sql_query("UNLOCK TABLES");
			$q = "Insert into " . EVENTDATES_TABLE . " (ed_division, ed_event, ed_date, ed_capacity, ed_serverPassword, ed_resultsPosted) values ";
			foreach ($this->dates as $key => $value)
			{
				$q = $q . "(" . $key . ", " . $insertID . ", '" . $value . "', " . $this->capacity[$key] . ", '" . $this->password[$key]  . "', '" . $value . "'),";
			}
			
			$q = substr($q , 0, -1);
			$db->sql_query($q);
			
			$qUpdateChamps = 'UPDATE ' . CHAMPIONSHIPS_TABLE . ' SET ' . 
					'c_firstRace=(SELECT ed_date FROM ' . EVENTDATES_TABLE . ' , ' . 
					DIVISIONS_TABLE . ' where ed_division = d_id  AND d_champid = ' .  
					$this->champid  . ' ORDER BY ed_date ASC LIMIT 0, 1),' . 
					'c_lastRace=(SELECT ed_date FROM ' . EVENTDATES_TABLE . ' , ' . 
					DIVISIONS_TABLE . ' where ed_division = d_id  AND d_champid = ' .  
					$this->champid  . ' ORDER BY ed_date DESC LIMIT 0, 1)' . 
					' WHERE c_id = ' . $this->champid;
			$db->sql_query($qUpdateChamps);
			
			$this->mess = new addMessage(str_replace('{entry}', $_POST['title'], $lang['AdminAdded']), $lang['AdminAddedTitle']);
		}
		else
		{
			$this->mess = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
		}
	}
	
	function doEdit()
	{
		global $db, $lang;
		
		if($this->validateFields(true)) 
		{
			$qUpd = "update  ". EVENTS_TABLE . " set e_title = '" . $_POST['title'] .
													  "', e_championship = " . $_POST['itemID'] .
													  ", e_track = " . $_POST['track']  .
													  ", e_opensignups = " . $_POST['active']  .
													  ", e_description = '" . $_POST['description']  .
													  "', e_preevent = '" . $_POST['preevent']  .
													  "', e_postevent = '" . $_POST['postevent']  .
													  "' WHERE e_id = " . $_POST['id'] ;
			$result = $db->sql_query($qUpd);
			
			//remove any existing records
			$q = "Delete from " . EVENTDATES_TABLE . " where  ed_event = " . $_POST['id'];
			$db->sql_query($q);
			
			//add the new entries
			$q = "Insert into " . EVENTDATES_TABLE . " (ed_division, ed_event, ed_date, ed_capacity, ed_serverPassword, ed_resultsPosted) values ";
			foreach ($this->dates as $key => $value)
			{
				$q = $q . "(" . $key . ", " . $_POST['id'] . ", '" . $value . "', " . $this->capacity[$key] . ", '" . $this->password[$key]  . "', '" . $value . "'),";
			}
			
			$q = substr($q , 0, -1);
			$db->sql_query($q);
			
			$qUpdateChamps = 'UPDATE ' . CHAMPIONSHIPS_TABLE . ' SET ' . 
					'c_firstRace=(SELECT ed_date FROM ' . EVENTDATES_TABLE . ' , ' . 
					DIVISIONS_TABLE . ' where ed_division = d_id  AND d_champid = ' .  
					$this->champid  . ' ORDER BY ed_date ASC LIMIT 0, 1),' . 
					'c_lastRace=(SELECT ed_date FROM ' . EVENTDATES_TABLE . ' , ' . 
					DIVISIONS_TABLE . ' where ed_division = d_id  AND d_champid = ' .  
					$this->champid  . ' ORDER BY ed_date DESC LIMIT 0, 1)' . 
					' WHERE c_id = ' . $this->champid;
			$db->sql_query($qUpdateChamps);
			
			$this->mess = new addMessage(str_replace('{entry}', $_POST['title'], $lang['AdminUpdated']), $lang['AdminUpdatedTitle']);
		}
		else
		{
			$this->mess = new addMessage($lang['DatabaseError'], $lang['DatabaseErrorTitle']);
		}
	}
	
	function validateFields($checkID = false)
	{
		global $db;
		
		$valid = true;
		$thisID = 0;
		
		if($checkID)
		{
			$valid = is_numeric($_POST['id']);
			$thisID = $_POST['id'];
		}
		
		
		
		$valid =  $valid && is_numeric($_POST['itemID'])
 					  && is_numeric($_POST['track'])
 					  && is_numeric($_POST['active'])
 					  && ($_POST['title'] != '');
		
		//get event dates			  
		if($valid)
		{
			$q = 'select d_id from ' . DIVISIONS_TABLE . ' where d_champid = ' . $this->champid;
			$result = $db->sql_query($q);
			while($row = $db->sql_fetchrow($result)) 
			{
				$object = 'date' . $row['d_id'] . '_' . $thisID;
				$checked = 'check' . $row['d_id'] . '_' . $thisID;
				if(isset($_POST[$object]) && $_POST[$object] != '' && isset($_POST[$checked]))
				{
					$this->dates[$row['d_id']] = $_POST[$object];
				}
				else
				{
					if(isset($_POST[$checked]))
						$valid = false;
				}
				
				$object = 'capacity' . $row['d_id'] . '_' . $thisID;
				if(isset($_POST[$object]) && is_numeric($_POST[$object]) && $_POST[$object] != '' && isset($_POST[$checked]))
				{
					$this->capacity[$row['d_id']] = $_POST[$object];
				}
				else
				{
					if(isset($_POST[$checked]))
						$valid = false;
				}
				
				$object = 'password' . $row['d_id'] . '_' . $thisID;
				if(isset($_POST[$object]) && isset($_POST[$checked]))
				{
					$this->password[$row['d_id']] = $_POST[$object];
				}
				else
				{
					if(isset($_POST[$checked]))
						$valid = false;
				}
			}
		}
		
		return $valid;	  
	}
	
	function setupEdit()
	{
		global $db, $lang;
		include_once('includes/addMessage.php');
		include_once('admin/edit_event.php');
		
		
		//get the record
		
		$q = "SELECT *, (SELECT ed_date FROM " . EVENTDATES_TABLE . " WHERE ed_event = e_id ORDER BY ed_date ASC limit 0, 1) AS ed_date FROM " . 
				EVENTS_TABLE . " WHERE e_championship = " . $this->champid . " ORDER BY ed_date ASC";
		$result = $db->sql_query($q);
		$introMess = false;
		
		while($row = $db->sql_fetchrow($result)) 
		{
			if(!$introMess)
			{
				$this->toRender[] = new addMessage($lang['AdminEdit'], $lang['AdminEditTitle']);
				$introMess = true;
			}
			
			$this->toRender[] = new edit_event(false, $this->champid, $this->tracks, $row);
		}
	}

	function setupAdd()
	{
		global $db, $lang;
		include_once('includes/addMessage.php');
		include_once('admin/edit_event.php');
		
		$q = "Select * From ". DIVISIONS_TABLE . " Where d_champid = " . $this->champid;
		$result = $db->sql_query($q);
		if($row = $db->sql_fetchrow($result)) 
		{
			$this->toRender[] = new addMessage($lang['AdminAdd'], $lang['AdminAddTitle']);
			$this->toRender[] = new edit_event(true, $this->champid, $this->tracks);
		}
		else
		{
			$this->toRender[] = new addMessage($lang['ErrorEventNoDivisions'], $lang['ErrorTitle']);
		}
		
		
	}

	
}
?>